package com.bw.utils.auth;

import com.alibaba.fastjson.JSON;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.joda.time.DateTime;

import java.security.PrivateKey;
import java.security.PublicKey;

public class JwtUtils {
    /**
     * 私钥加密token
     *
     * @param userInfo      载荷中的数据
     * @param privateKey    私钥
     * @param expireMinutes 过期时间，单位秒
     * @return
     * @throws Exception
     */
    public static String generateToken(UserInfo userInfo, PrivateKey privateKey, int expireMinutes) throws Exception {
        return Jwts.builder()
                .claim(JwtConstans.JWT_KEY_ID, userInfo.getId())
                .claim(JwtConstans.JWT_KEY_USER_NAME, userInfo.getUsername())
                .setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate())
                .signWith(SignatureAlgorithm.RS256, privateKey)
                .compact();
    }

    /**
     * 私钥加密token
     *
     * @param userInfo      载荷中的数据
     * @param privateKey    私钥字节数组
     * @param expireMinutes 过期时间，单位秒
     * @return
     * @throws Exception
     */
    public static String generateToken(UserInfo userInfo, byte[] privateKey, int expireMinutes) throws Exception {
        return Jwts.builder()
                .claim(JwtConstans.JWT_KEY_ID, userInfo.getId())
                .claim(JwtConstans.JWT_KEY_USER_NAME, userInfo.getUsername())
                .setExpiration(DateTime.now().plusMinutes(expireMinutes).toDate())
                .signWith(SignatureAlgorithm.RS256, RsaUtils.getPrivateKey(privateKey))
                .compact();
    }

    /**
     * 公钥解析token
     *
     * @param token     用户请求中的token
     * @param publicKey 公钥
     * @return
     * @throws Exception
     */
    private static Jws<Claims> parserToken(String token, PublicKey publicKey) {
        return Jwts.parser().setSigningKey(publicKey).parseClaimsJws(token);
    }

    /**
     * 公钥解析token
     *
     * @param token     用户请求中的token
     * @param publicKey 公钥字节数组
     * @return
     * @throws Exception
     */
    private static Jws<Claims> parserToken(String token, byte[] publicKey) throws Exception {
        return Jwts.parser().setSigningKey(RsaUtils.getPublicKey(publicKey))
                .parseClaimsJws(token);
    }

    /**
     * 获取token中的用户信息
     *
     * @param token     用户请求中的令牌
     * @param publicKey 公钥
     * @return 用户信息
     * @throws Exception
     */
    public static UserInfo getInfoFromToken(String token, PublicKey publicKey) throws Exception {
        Jws<Claims> claimsJws = parserToken(token, publicKey);
        Claims body = claimsJws.getBody();
        return new UserInfo(
                ObjectUtils.toLong(body.get(JwtConstans.JWT_KEY_ID)),
                ObjectUtils.toString(body.get(JwtConstans.JWT_KEY_USER_NAME))
        );
    }

    /**
     * 获取token中的用户信息
     *
     * @param token     用户请求中的令牌
     * @param publicKey 公钥
     * @return 用户信息
     * @throws Exception
     */
    public static UserInfo getInfoFromToken(String token, byte[] publicKey) throws Exception {
        Jws<Claims> claimsJws = parserToken(token, publicKey);
        Claims body = claimsJws.getBody();
        return new UserInfo(
                ObjectUtils.toLong(body.get(JwtConstans.JWT_KEY_ID)),
                ObjectUtils.toString(body.get(JwtConstans.JWT_KEY_USER_NAME))
        );
    }

    public static void main(String[] args) throws Exception {
        /*try {
            PublicKey  publicKey = RsaUtils.getPublicKey("D:\1711A\keys\rsa.pub");
            UserInfo userInfo=JwtUtils.getInfoFromToken("eyJhbGciOiJSUzI1NiJ9.eyJpZCI6MjksInVzZXJuYW1lIjoieHMwMSIsImV4cCI6MTU3Njk0NjgzNX0.TOsEZ4nG3u0n-WzWtCZrtAkbpWG2dK9yWdYisWrKE6Jqn5biCcwGPyzOzYWzIVPbKm30m6CCa_faDc4-w0y_7ACgGA0ZAoXXdfpZPGDqdzuNzCEzMGwRJ9LmXVNSzA63ZP81iLbasjNtQSaodMgGoJcjoMSF-oxhQkmrU-xVjCw",publicKey);
            System.out.println(userInfo);
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        //获取私钥
        //PrivateKey privateKey=RsaUtils.getPrivateKey("D:\\1711A\\keys\\rsa.pri");
        //颁发令牌
//        String token="eyJhbGciOiJSUzI1NiJ9.eyJpZCI6MSwidXNlcm5hbWUiOiJ6aGFuZ3NhbiIsImV4cCI6MTU5MDA0NDg4M30.cLjF3rYkgsRY-3BiqyNqEUbRuKzeE4VxEiCC_pQnzEln1QAOAw6tNZ-EsJDbR7mtKY2bRSg5gJIdeyfjLxl3dx7Jpu6JHpEfw7k1wyB6FpVWh9aXAsGIchZ-5MUKN-OxjRsofVR4GvoqetjBC869Q572nckcRxq6qWuV2dK_Kpo"
//        UserInfo userInfo = new UserInfo();
//        userInfo.setId(1L);
//        userInfo.setUsername("zhangsan");
//        String token = JwtUtils.generateToken(userInfo, privateKey, 30);
//        System.out.println(token);
       //验证令牌
        String token="eyJhbGciOiJSUzI1NiJ9.eyJpZCI6MiwidXNlcm5hbWUiOiJsaXNpIiwiZXhwIjoxNTkwMDY1MjkyfQ.bbt7VqC0yTgh1fT-ec-XoZEAg4sW2i3xWIHvipJsCVOacWFV43_ZD0VC0q4mUPnXphM39woR2DEPMwDSz4_6vd8BjNzZpNwYP7h9FBcXbPEsE0Uj5rVQP3M-I0uac67J5H1yJQtNXt4P3w3aP33yK5AQvjL4pEMwtlYp6ACiGcI";
        PublicKey publicKey = RsaUtils.getPublicKey("D:\\1711A\\keys\\rsa.pub");
        UserInfo userInfo = JwtUtils.getInfoFromToken(token, publicKey);
        String s = JSON.toJSONString(userInfo);
        System.out.println(s);
    }
}